package com.hanxiaozhang.no6oom;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;

import java.util.concurrent.TimeUnit;


/**
 * 功能描述: <br>
 * 〈Metaspace空间溢出〉
 * <p>
 * JVM参数：
 * -XX:MetaspaceSize=12m -XX:MaxMetaspaceSize=12m
 *
 * @Author: hanxinghua
 * @Date: 2023/11/30
 */
public class No3MetaspaceOOM {
    public static void main(String[] args) {

        // 元空间溢出线程
        new Thread(() -> {
            try {
                while (true) {
                    // 使用GCLib创建对象，类信息存储在元空间。
                    Enhancer enhancer = new Enhancer();
                    enhancer.setSuperclass(OOMTest.class);
                    enhancer.setUseCache(false);
                    enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> methodProxy.invoke(o, args));
                    enhancer.create();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }).start();

        // 正常线程
        new Thread(() -> {
            int num = 0;
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(num);
                num++;
            }
        }).start();


    }

    static class OOMTest {
    }

}
